package com.hengxinguotong.zhihuichengjian.ui.app;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.exception.CrashHandler;
import com.hengxinguotong.zhihuichengjian.utils.FileUtil;
import com.hik.mcrsdk.MCRSDK;
import com.hik.mcrsdk.rtsp.RtspClient;
import com.hikvision.sdk.VMSNetSDK;
import com.inpor.fastmeetingcloud.sdk.HstLoginManager;
import com.pgyersdk.crash.PgyCrashManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import cn.jiguang.analytics.android.api.JAnalyticsInterface;
import cn.jiguang.share.android.api.JShareInterface;
import cn.jpush.android.api.JPushInterface;
import dagger.android.AndroidInjector;
import dagger.android.DaggerApplication;

/**
 * Application 类
 */
public class MyApp extends DaggerApplication
{
    private static MyApp ins;
    public static String ImagePath;

    /**
     * 分割 Dex 支持
     *
     * @param base
     */
    @Override
    protected void attachBaseContext(Context base)
    {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        JPushInterface.setDebugMode(true);    // 设置日志,发布时请关闭日志
        JPushInterface.init(this);            // 初始化JPush
        JAnalyticsInterface.init(this);
        JAnalyticsInterface.initCrashHandler(this);
        PgyCrashManager.register(this);
        //初始化视频会议SDK
        HstLoginManager.getInstance().initSdk(getApplicationContext());
        ins = this;
//        initHK();
        clearImagCache();
//        if (!Utils.isDebugVersion(this))
//        {
            //全局收集异常信息的单例类
//            CrashHandler crashHandler = CrashHandler.getInstance();//这是收集异常信息的单例类
//            crashHandler.init(getApplicationContext());//初始化
            CrashHandler crashHandler = CrashHandler.getInstance();
            crashHandler.init(this);
//        }
        JShareInterface.setDebugMode(true);
        JShareInterface.init(this);
        new Thread()
        {
            @Override
            public void run()
            {
                File imageFile = copyResurces("zhihuichengjian.png", "zhihuichengjian.png", 0);
                if (imageFile != null)
                {
                    ImagePath = imageFile.getAbsolutePath();
                }
                super.run();
            }
        }.start();
    }

    @Override
    protected AndroidInjector<? extends DaggerApplication> applicationInjector()
    {
        return DaggerAppComponent.builder()
                .application(this)
                .gson(new Gson())
                .build();
    }

    private File copyResurces(String src, String dest, int flag)
    {
        File filesDir = null;
        try
        {
            if (flag == 0)
            {//copy to sdcard
                filesDir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/escst/" + dest);
                File parentDir = filesDir.getParentFile();
                if (!parentDir.exists())
                {
                    parentDir.mkdirs();
                }
            } else
            {//copy to data
                filesDir = new File(getFilesDir(), dest);
            }
            if (!filesDir.exists())
            {
                filesDir.createNewFile();
                InputStream open = getAssets().open(src);
                FileOutputStream fileOutputStream = new FileOutputStream(filesDir);
                byte[] buffer = new byte[4 * 1024];
                int len = 0;
                while ((len = open.read(buffer)) != -1)
                {
                    fileOutputStream.write(buffer, 0, len);
                }
                open.close();
                fileOutputStream.close();
            }
        } catch (IOException e)
        {
            e.printStackTrace();
            if (flag == 0)
            {
                filesDir = copyResurces(src, dest, 1);
            }
        }
        return filesDir;
    }


    private void initHK()
    {
        new AsyncTask<Void, Void, Void>()
        {
            @Override
            protected Void doInBackground(Void... voids)
            {
                MCRSDK.init();
                RtspClient.initLib();
                MCRSDK.setPrint(1, null);
                VMSNetSDK.init(MyApp.this);
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid)
            {
            }
        }.execute();
    }

    private void clearImagCache()
    {
        new AsyncTask<Void, Void, Void>()
        {
            @Override
            protected Void doInBackground(Void... voids)
            {
                deleteFolderFile(FileUtil.imageDir1, false);
                return null;
            }
        }.execute();
    }


    /**
     * 删除指定目录下文件及目录
     *
     * @param deleteThisPath
     * @return
     */
    public void deleteFolderFile(String filePath, boolean deleteThisPath)
    {
        if (!TextUtils.isEmpty(filePath))
        {
            try
            {
                File file = new File(filePath);
                if (file.isDirectory())
                {// 处理目录
                    File files[] = file.listFiles();
                    for (int i = 0; i < files.length; i++)
                    {
                        deleteFolderFile(files[i].getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath)
                {
                    if (!file.isDirectory())
                    {// 如果是文件，删除
                        file.delete();
                    } else
                    {// 目录
                        if (file.listFiles().length == 0)
                        {// 目录下没有文件或者目录，删除
                            file.delete();
                        }
                    }
                }
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    public static MyApp getIns()
    {
        return ins;
    }

}
